﻿using System.IO;
using System.Text;

namespace HighPerformanceLog
{
    /// <summary>
    /// 包含大量通用静态函数。
    /// </summary>
    public class Common
    { 
        /// <summary>
        /// 将数据写入到指定文件。
        /// </summary>
        /// <param name="fileName">待写入的文件名。</param>
        /// <param name="text">待写入的文本内容。</param>
        /// <param name="append">是否为追加模式，默认为true。</param>
        /// <param name="encoding">编码，默认为UTF-8。</param>
        public static void WriteTextToFile(string fileName, string text, bool append = true, string encoding = "utf-8")
        {
            Encoding _encoding = Encoding.Default;
            if(encoding.ToLower() == "utf8" || encoding.ToLower() == "utf-8")
            {
                _encoding = Encoding.UTF8;
            }

            var fullpath = Path.GetFullPath(fileName);
            // 使用线程锁，用于解决不同线程间资源竞争所导致的错误。
            lock (fullpath)
            {
                using(StreamWriter sw = new StreamWriter(fullpath, append, _encoding))
                {
                    sw.WriteLine(text);
                }
            }
        }
    }
}
